package com.zhiyou.aifeng.smart_machine

import android.os.Bundle
import android.view.View
import com.jeremyliao.liveeventbus.utils.observe
import com.zhiyou.aifeng.common.base.gone
import com.zhiyou.aifeng.common.base.makeCall
import com.zhiyou.aifeng.common.base.visible
import com.zhiyou.aifeng.common.helper.*
import com.zhiyou.aifeng.common_ui.base.BaseActivity
import com.zhiyou.aifeng.common_ui.base.addItems
import com.zhiyou.aifeng.common_ui.base.loadLinear
import com.zhiyou.aifeng.common_ui.base.refresh
import com.zhiyou.aifeng.common_ui.model.BaseUrl
import com.zhiyou.aifeng.common_ui.model.CommonData
import com.zhiyou.aifeng.common_ui.utils.showHintDialog
import com.zhiyou.aifeng.common_ui.utils.showInputDialog
import com.zhiyou.aifeng.utils.onTabSelectedListener
import com.zhiyou.aifeng.utils.setEmptyIcon
import com.zhiyou.aifeng.viewmodel.OrderViewModel
import kotlinx.android.synthetic.main.activity_order.*
import kotlinx.android.synthetic.main.layout_empty.*
import kotlinx.android.synthetic.main.layout_list.*
import net.idik.lib.slimadapter.SlimAdapter
import org.jetbrains.anko.startActivity
import org.jetbrains.anko.toast

class OrderActivity : BaseActivity() {

    private var mState = ""

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_order)
        initTitle(title = "我的作业订单", divider = false)
    }

    override fun getViewModel() = get<OrderViewModel>()

    override fun initTitle(title: String, name: String, divider: Boolean) {
        super.initTitle(title, name, divider)
        initTabLayout()
        initList()

        observe("orderList") { value ->
            val items = value.split(",")
            if (mList.any { (it as CommonData).njsjid == items[0] }) {
                val index = mList.indexOfFirst { (it as CommonData).njsjid == items[0] }
                if (mState.isNotEmpty()) {
                    mList.removeAt(index)
                    mAdapter.notifyItemRemoved(index)
                    empty_view.apply { if (mList.isEmpty()) visible() else gone() }
                } else {
                    (mList[index] as CommonData).allot_state = items[1]
                    if (items[1] == "4")
                        (mList[index] as CommonData).real_area = items[2]
                    mAdapter.notifyItemChanged(index)
                }
            }
        }
    }

    private fun initTabLayout() {
        order_tab.apply {
            onTabSelectedListener {
                onTabSelected {
                    mState = when (it!!.position) {
                        1 -> "2"
                        2 -> "3"
                        3 -> "4"
                        else -> ""
                    }

                    getViewModel().cancelRequest()
                    getViewModel().delay { updateList() }
                }
            }
            addTab(newTab().setText("全部"), true)
            addTab(newTab().setText("已接单"), false)
            addTab(newTab().setText("作业中"), false)
            addTab(newTab().setText("已完成"), false)
        }
    }

    private fun initList() {
        empty_img.setEmptyIcon()
        empty_hint.text = "暂无相关订单信息！"
        swipe_refresh.refresh { getData(1) }
        recycle_list.apply {
            loadLinear(baseContext, swipe_refresh) {
                if (!isLoadingMore) {
                    isLoadingMore = true
                    getData(pageNum)
                }
            }

            mAdapter = SlimAdapter.create()
                .register<CommonData>(R.layout.item_order_list) { data, injector ->

                    val index = mList.indexOf(data)
                    val isLast = index == mList.size - 1

                    injector.text(R.id.item_order_code, "订单编号：${data.work_code}")
                        .text(R.id.item_order_type, data.work_type_name)
                        .text(
                            R.id.item_order_hint,
                            if (data.allot_state == "4" || data.allot_state == "5") "实际作业面积：" else "作业面积："
                        )
                        .text(
                            R.id.item_order_square,
                            "${if (data.allot_state == "4" || data.allot_state == "5") data.real_area.formatDecimal() else data.area.formatDecimal()}亩"
                        )
                        .text(
                            R.id.item_order_time,
                            data.preset_date.getTimeString("yyyy-MM-dd HH:mm")
                        )
                        .text(
                            R.id.item_order_adress,
                            data.region_addr.replace(" ", "") + data.address
                        )
                        .text(
                            R.id.item_order_status,
                            when (data.allot_state) {
                                "2" -> "已接单"
                                "3" -> "作业中"
                                "4", "5" -> "已完成"
                                else -> ""
                            }
                        )
                        .visibility(
                            R.id.item_order_ping,
                            if (data.allot_state == "5") View.VISIBLE else View.GONE
                        )
                        .visibility(
                            R.id.item_order_btn1,
                            when (data.allot_state) {
                                "3", "4", "5" -> View.VISIBLE
                                else -> View.GONE
                            }
                        )
                        .visibility(
                            R.id.item_order_btn3,
                            when (data.allot_state) {
                                "2" -> View.VISIBLE
                                else -> View.GONE
                            }
                        )
                        .visibility(
                            R.id.item_order_btn4,
                            when (data.allot_state) {
                                "2" -> View.VISIBLE
                                else -> View.GONE
                            }
                        )
                        .visibility(
                            R.id.item_order_btn5,
                            when (data.allot_state) {
                                "3" -> View.VISIBLE
                                else -> View.GONE
                            }
                        )
                        .visibility(
                            R.id.item_order_divider,
                            if (isLast) View.VISIBLE else View.GONE
                        )
                        .clicked(R.id.item_order_btn1) {
                            if (data.contact_phone.isNotEmpty()) {
                                showHintDialog(
                                    title = "提示",
                                    hint = "确定要拨打联系农户吗？"
                                ) { makeCall(data.contact_phone) }
                            }
                        }
                        .clicked(R.id.item_order_btn2) {
                            if (getString("serviceTel").isNotEmpty()) {
                                showHintDialog(
                                    title = "提示",
                                    hint = "确定要拨打联系客服吗？"
                                ) { makeCall(getString("serviceTel")) }
                            }
                        }
                        .clicked(R.id.item_order_btn3) {
                            if (data.contact_phone.isNotEmpty()) {
                                showHintDialog(
                                    title = "提示",
                                    hint = "确定要拨打联系农户吗？"
                                ) { makeCall(data.contact_phone) }
                            }
                        }
                        .clicked(R.id.item_order_btn4) { startOrder(data.njsjid, index) }
                        .clicked(R.id.item_order_btn5) {
                            endOrder(
                                data.njsjid,
                                index,
                                if (data.count.toNotInt() > 1) "" else data.area.formatDecimal()
                            )
                        }
                        .clicked(R.id.item_order) {
                            startActivity<OrderDetailActivity>("orderId" to data.njsjid)
                        }

                }
                .attachTo(this)
        }
    }

    private fun startOrder(dataId: String, index: Int) {
        showHintDialog(
            title = "开始作业",
            hint = "是否确认开始作业？"
        ) {
            getViewModel().request(
                requestUrl = BaseUrl.workStart,
                params = *arrayOf(
                    "uid" to getString("userId"),
                    "njsjid" to dataId
                ),
                onResult = {
                    toast("作业已开始！")
                    if (mState.isNotEmpty()) {
                        mList.removeAt(index)
                        mAdapter.notifyItemRemoved(index)
                        empty_view.apply { if (mList.isEmpty()) visible() else gone() }
                    } else {
                        (mList[index] as CommonData).allot_state = "3"
                        mAdapter.notifyItemChanged(index)
                    }
                }
            )
        }
    }

    private fun endOrder(dataId: String, index: Int, default: String) {
        showInputDialog(default) { value ->
            getViewModel().request(
                requestUrl = BaseUrl.workDone,
                params = *arrayOf(
                    "uid" to getString("userId"),
                    "njsjid" to dataId,
                    "area" to value
                ),
                onResult = {
                    toast("作业已结束！")
                    if (mState.isNotEmpty()) {
                        mList.removeAt(index)
                        mAdapter.notifyItemRemoved(index)
                        empty_view.apply { if (mList.isEmpty()) visible() else gone() }
                    } else {
                        (mList[index] as CommonData).allot_state = "4"
                        (mList[index] as CommonData).real_area = value
                        mAdapter.notifyItemChanged(index)
                    }
                }
            )
        }
    }

    override fun getData(index: Int, isLoading: Boolean) {
        getViewModel().requestCommon(
            requestUrl = BaseUrl.orderList,
            params = *arrayOf(
                "uid" to getString("userId"),
                "allot_state" to mState,
                "page" to index
            ),
            onSuccess = {
                mList.apply {
                    if (index == 1) {
                        clear()
                        pageNum = index
                    }
                    addItems(it)
                    if (it.count() > 0) pageNum++
                }

                mAdapter.updateData(mList)
            },
            onFinally = {
                swipe_refresh.isRefreshing = false
                isLoadingMore = false
                empty_view.apply { if (mList.isEmpty()) visible() else gone() }
            }
        )
    }

    private fun updateList() {
        swipe_refresh.isRefreshing = true

        empty_view.gone()
        if (mList.isNotEmpty()) {
            mList.clear()
            mAdapter.notifyDataSetChanged()
        }

        pageNum = 1
        getData(pageNum)
    }

}